#include						"Processor.h"
#include						<iostream>

Processor::Processor()
{
#ifdef __linux__
	_plugin = new PluginManager("../Plugins", _api);
#else
	_plugin = new PluginManager("../Win32/Debug", _api);
#endif
}

Processor::~Processor()
{
	while (!_order.empty())
	{
		IOrder * order = _order.front();
		_order.pop();
		delete order;
	}
	delete _plugin;
}

void							Processor::update()
{
	std::cout << "The message queue's size is: "<< _order.size() << std::endl;
}

void							Processor::processOrder(IOrder *order)
{
	IModule	*	plugin;
	Protocol	*proto = (Protocol*)order->getData(sizeof(Protocol));

	if (proto == NULL)
	{
		delete order;
		return;
	}
	plugin = _plugin->getPluginProtocol(*proto);
	if (plugin != NULL)
		plugin->takeOrder(order, *proto);
	else
	{
		std::cout << "unknown protocol " << *proto << " received" << std::endl;
		delete order;
	}
}

void							Processor::operator()(std::vector<byte> *order, unsigned short id)
{
	IOrder						*neworder = new Order;

	neworder->setData(order);
	neworder->setSenderId(id);
	processOrder(neworder);
}

IOrder							*Processor::_pop()
{
	_mutex.lock();
	IOrder * order = _order.front();
	_order.pop();
	_mutex.unlock();
	return order;
}

void							Processor::_push(IOrder * order)
{
	_mutex.lock();
	_order.push(order);
	_mutex.unlock();
}


void							Processor::setAPI(BabelApi* api)
{
	_api = api;
	_plugin->setApi(api);
	_plugin->load();
}
